//
//  GJAlertView.m
//  YDGJ
//
//  Created by 黄卫 on 17/2/24.
//  Copyright © 2017年 huangwei. All rights reserved.
//

#import "GJAlertView.h"
#import "FD_Method.h"

// 按钮高度
#define ActionSheetButtonHeight 44.0f
#define ActionSheetCancelbtnSpace 10.0f

@interface GJAlertView ()

@property (nonatomic, strong) UIView   *contentView;
@property (nonatomic, copy) void(^buttonBlock)(NSInteger buttonIndex);
@property (nonatomic, copy) void(^cancelBlock)();
/** ActionSheet所有按钮数组 */
@property (nonatomic, strong) NSMutableArray *actionSheetButtonArr;

@end

@implementation GJAlertView


//============================================ 系统UIAlertView弹框 ==========================================

+ (void)alertWithCallBackBlock:(UIAlertViewCallBackBlock)alertViewCallBackBlock title:(NSString *)title message:(NSString *)message  cancelButtonName:(NSString *)cancelButtonName otherButtonTitles:(NSString *)otherButtonTitles, ...NS_REQUIRES_NIL_TERMINATION
{
    //防止页面上其他弹框
    [MBProgressHUD hideLoadingFromWindow];
    if (KsystemVersion < 8.0){ // iOS8以前系统弹框
    
        [UIAlertView alertWithCallBackBlock:^(NSInteger buttonIndex) {
            if(alertViewCallBackBlock){
                alertViewCallBackBlock(buttonIndex);
            }
        } title:title message:message cancelButtonName:cancelButtonName otherButtonTitles:otherButtonTitles, nil];
        
    } else { //ios8以后系统弹框
        
        //获取按钮个数
        NSMutableArray *mutableOtherTitles = [NSMutableArray array];
        va_list otherButtonTitleList;
        va_start(otherButtonTitleList, otherButtonTitles);
        {
            for (NSString *otherButtonTitle = otherButtonTitles; otherButtonTitle != nil; otherButtonTitle = va_arg(otherButtonTitleList, NSString *)) {
                [mutableOtherTitles addObject:otherButtonTitle];
            }
        }
        va_end(otherButtonTitleList);
        
        //按钮至少要有一个
        if(mutableOtherTitles.count == 0 && !cancelButtonName) return;
        
        //防止传入错误参数
        if(title && ![title isKindOfClass:[NSString class]]) {
            title = @"标题错误!";
        }
        
        if(message && ![message isKindOfClass:[NSString class]]) {
            message = @"提示信息错误!";
        }
        
        //弹出ios 8 以上的系统框
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
       
        //如果按钮个数大于两个, 则把 "取消"按钮放最后, 否则放第一个
        if (mutableOtherTitles.count>1) { //多个按钮时,系统布局会有差别
        
            //普通按钮放前面
            for(int i=0; i<mutableOtherTitles.count; i++) {
                [alertController addAction:[UIAlertAction actionWithTitle:mutableOtherTitles[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    if(alertViewCallBackBlock){
                        
                        if(cancelButtonName){
                            alertViewCallBackBlock(i+1);//取消按钮放在第一个,所以要加1
                        } else {
                            alertViewCallBackBlock(i);
                        }
                    }
                }]];
            }
            
            //取消按钮放最后
            if(cancelButtonName)
            {
                [alertController addAction:[UIAlertAction actionWithTitle:cancelButtonName style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    if(alertViewCallBackBlock){
                        alertViewCallBackBlock(0);
                    }
                }]];
            }
            
            
            /** 设置颜色*/
            if([FD_Method getVariableWithClass:alertController.actions.firstObject varName:@"titleTextColor"])
            {
                for(int i = 0;i < alertController.actions.count;i++)
                {
                    UIAlertAction *action = alertController.actions[i];
                    if(i == alertController.actions.count-1)
                    {
                        [action setValue:Color_Main forKey:@"titleTextColor"];//黄色
                    } else {
                        [action setValue:GJNabBarBackColor forKey:@"titleTextColor"];
                    }
                }
            }
            
        
        } else
        {  //只有一个或两个按钮的情况
        
            //取消按钮放前面
            if(cancelButtonName)
            {
                [alertController addAction:[UIAlertAction actionWithTitle:cancelButtonName style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    if(alertViewCallBackBlock){
                        alertViewCallBackBlock(0);
                    }
                }]];
            }
            
            //普通按钮放最后
            for(int i=0; i<mutableOtherTitles.count; i++) {
                [alertController addAction:[UIAlertAction actionWithTitle:mutableOtherTitles[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    if(alertViewCallBackBlock){
                        
                        if(cancelButtonName){
                            alertViewCallBackBlock(i+1);//取消按钮放在第一个,所以要加1
                        } else {
                            alertViewCallBackBlock(i);
                        }
                    }
                }]];
            }
            
            /** 设置颜色*/
            if([FD_Method getVariableWithClass:alertController.actions.firstObject varName:@"titleTextColor"])
            {
                for(int i = 0;i < alertController.actions.count;i++)
                {
                    UIAlertAction *action = alertController.actions[i];
                    if(alertController.actions.count == 1)
                    {
                        [action setValue:Color_Main forKey:@"titleTextColor"];//黄色
                        
                    } else if (alertController.actions.count == 2) {
                        
                        if(i == 0){
                            [action setValue:GJNabBarBackColor forKey:@"titleTextColor"];
                        } else {
                            [action setValue:Color_Main forKey:@"titleTextColor"];
                        }
                    }
                }
            }

        }
      
        //** 设置字体为细体
        if([FD_Method getVariableWithClass:alertController varName:@"attributedTitle"])
        {
            if(title){
                NSAttributedString *titleAttrs = [[NSAttributedString alloc] initWithString:title attributes:@{NSForegroundColorAttributeName: UIColorFromRGB(0x323232), NSFontAttributeName: FontCustomSize(16)}];
                [alertController setValue:titleAttrs forKey:@"attributedTitle"];
            }
            
            if(message && [FD_Method getVariableWithClass:alertController varName:@"_attributedMessage"]){
                NSAttributedString *messageAttrs = [[NSAttributedString alloc] initWithString:message attributes:@{NSForegroundColorAttributeName: UIColorFromRGB(0x323232), NSFontAttributeName: FontCustomSize(16)}];
                [alertController setValue:messageAttrs forKey:@"_attributedMessage"];
            }
            
            if (title.length && [title rangeOfString:@"picture.1dian.la"].location != NSNotFound)
            {
                [alertController setValue:[NSString alertTitleForCopyLink] forKey:@"attributedTitle"];
            }
        }
        
        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        [window.rootViewController presentViewController:alertController animated:YES completion:nil];
    }
}

#pragma mark ==================================== 仿ActionSheet弹框 ======================================

+ (instancetype)actionSheetBCallBlock:(UIAlertViewCallBackBlock)buttonBlock cancelBlock:(void (^)())cancelBlock WithTitle:(id)title cancelButtonTitle:(id)cancelButtonTitle otherButtonTitleArr:(NSArray *)otherButtonTitleArr
{
    //按钮至少要有一个
    if(otherButtonTitleArr.count == 0 && !cancelButtonTitle) return nil;
    
    return [[self alloc] initWithFrame:[UIScreen mainScreen].bounds title:title cancelButtonName:cancelButtonTitle buttonTitleArr:otherButtonTitleArr block:buttonBlock cancelBlock:cancelBlock];
}

#pragma mark - 自定义ActionSheet

- (instancetype)initWithFrame:(CGRect)frame title:(id)title cancelButtonName:(id)cancelTitle buttonTitleArr:(NSArray *)buttonTitleArr block:(UIAlertViewCallBackBlock)callBackBlock  cancelBlock:(void (^)())cancelBlock
{
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {
        self.buttonBlock = callBackBlock;
        self.cancelBlock = cancelBlock;
        
        self.alpha = 0.0;
        self.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.4];
        
        //点击背景消失
        UIControl *control = [[UIControl alloc] initWithFrame:self.frame];
        [control addTarget:self action:@selector(dismissGJActionSheet:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:control];
        
        //创建ActionSheet按钮
        [self initSquareActionSheetUI:title cancelTitle:cancelTitle buttonTitleArr:buttonTitleArr];
        
        //显示在窗口
        [self showGJActionSheet];
    }
    return self;
}

/**
 *  ActionSheet所有按钮数组
 */
- (NSMutableArray *)actionSheetButtonArr
{
    if (!_actionSheetButtonArr) {
        _actionSheetButtonArr = [NSMutableArray array];
    }
    return _actionSheetButtonArr;
}

#pragma mark -================================== 创建圆角的ActionSheet =====================================

/**
 *  创建圆角的ActionSheet
 */
- (void)initCornerRadiusActionSheetUI:(id)title cancelTitle:(id)cancelTitle buttonTitleArr:(NSArray *)buttonTitleArr
{
    CGFloat contentViewH = ActionSheetButtonHeight;
    
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(KViewLineSpacing, Screen_Height-(KViewLineSpacing+ActionSheetCancelbtnSpace), Screen_Width-KViewLineSpacing*2, contentViewH)];
    contentView.backgroundColor = [UIColor clearColor];
    [self addSubview:contentView];
    self.contentView = contentView;
    
    //上半部分按钮
    UIView *aboveView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, contentView.width, contentViewH)];
    aboveView.backgroundColor = [UIColor clearColor];
    aboveView.layer.cornerRadius = 5;
    aboveView.layer.masksToBounds = YES;
    [contentView addSubview:aboveView];
    
    //最后一个按钮的高度
    CGFloat titleHY = 0;
    
    //是否有标题
    if (title)
    {
        CGFloat fontNum = 17;
        UILabel *titleLab = [[UILabel alloc] init];
        titleLab.backgroundColor = UIColorFromRGB(0xf5f5f5);
        [titleLab setTextColor:UIColorFromRGB(0x666666)];
        [titleLab setTextAlignment:NSTextAlignmentCenter];
        [titleLab setFont:FontCustomSize(fontNum)];
//        [titleLab setBackgroundColor:WhiteColor];
        titleLab.numberOfLines = 0;
        [aboveView addSubview:titleLab];
        
        //根据文字类型设置标题
        NSString *titleString = nil;
        CGFloat btnHeight = ActionSheetButtonHeight;
        if ([title isKindOfClass:[NSString class]])
        {
            titleString = title;
            [titleLab setText:title];
        } else if([title isKindOfClass:[NSAttributedString class]]){
            [titleLab setAttributedText:title];
            titleString = ((NSAttributedString *)title).string;
        }
        
        if ([FD_Method stringSize:titleString andFont:titleLab.font andwidth:MAXFLOAT].height > fontNum+2)
        {
            btnHeight +=10;
        }

        [titleLab setFrame:CGRectMake(0, 0, aboveView.width, btnHeight)];

        titleHY = CGRectGetMaxY(titleLab.frame);
    }
    
    //所有按钮标题
    NSMutableArray *allbuttontitleArr = [NSMutableArray arrayWithArray:buttonTitleArr];
    if (cancelTitle) {
        [allbuttontitleArr addObject:cancelTitle];
    }
    
    [self.actionSheetButtonArr removeAllObjects];
    //设置所有按钮
    for (int i = 0 ; i<allbuttontitleArr.count; i++) {
        
        UIButton *actionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [actionBtn setSize:CGSizeMake(aboveView.width, ActionSheetButtonHeight)];
        actionBtn.backgroundColor = WhiteColor;
        [actionBtn setTitleColor:Color_BlackFont forState:0];
        [actionBtn.titleLabel setFont:FontCustomSize(16)];
        [actionBtn setTitleColor:Color_BlackFont forState:0];
        [actionBtn addTarget:self action:@selector(actionBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [actionBtn setTitleColor:RGB(231, 231, 231) forState:UIControlStateDisabled];
        [actionBtn setBackgroundColor:RGB(231, 231, 231) forState:UIControlStateHighlighted];
        [actionBtn setExclusiveTouch:YES];
        
        //添加所有actionSheet按钮
        [self.actionSheetButtonArr addObject:actionBtn];
        
        //取消按钮
        if (cancelTitle && i == allbuttontitleArr.count-1)
        {
            actionBtn.tag = 0;
            actionBtn.layer.cornerRadius = 5;
            actionBtn.layer.masksToBounds = YES;
            actionBtn.y = CGRectGetMaxY(aboveView.frame)+ActionSheetCancelbtnSpace;
            [actionBtn setTitleColor:Color_Main forState:0];
            [contentView addSubview:actionBtn];
            
            //设置整体contentView高度
            contentView.height = CGRectGetMaxY(aboveView.frame);
            
        } else { //上半部分普通按钮
            actionBtn.tag = i+1;
            actionBtn.y = titleHY + ActionSheetButtonHeight*i;
            [aboveView addSubview:actionBtn];
            
            //设置上半部分按钮整体高度
            aboveView.height = CGRectGetMaxY(actionBtn.frame);
        }
        
        //根据文字类型设置标题
        id buttonTitle = allbuttontitleArr[i];
        if ([buttonTitle isKindOfClass:[NSString class]]) {
            [actionBtn setTitle:buttonTitle forState:0];
            
        } else if([buttonTitle isKindOfClass:[NSAttributedString class]]){
            [actionBtn setAttributedTitle:buttonTitle forState:0];
        }
        
        //线条
        UIImageView *line = [[UIImageView alloc] init];
        [line setImage:[UIImage imageNamed:@"cellLine"]];
        [line setFrame:CGRectMake(10, 0, contentView.width-20, 0.5f)];
        [actionBtn addSubview:line];
        
        contentView.height = CGRectGetMaxY(actionBtn.frame)+KViewLineSpacing;
    }
    
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    [window endEditing:YES];
    [window addSubview:self];
}

#pragma mark -================================== 创建直角的ActionSheet =====================================

/**
 *  创建直角的ActionSheet
 */
- (void)initSquareActionSheetUI:(id)title cancelTitle:(id)cancelTitle buttonTitleArr:(NSArray *)buttonTitleArr
{
    CGFloat contentViewH = ActionSheetButtonHeight;
    
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, Screen_Height, Screen_Width, contentViewH)];
    contentView.backgroundColor = Color_BackGround;
    [self addSubview:contentView];
    self.contentView = contentView;
    
    //最后一个按钮的高度
    CGFloat titleHY = 0;
    
    //是否有标题
    if (title)
    {
        UILabel *titleLab = [[UILabel alloc] init];
        titleLab.backgroundColor = UIColorFromRGB(0xf5f5f5);
        [titleLab setTextColor:UIColorFromRGB(0x666666)];
        [titleLab setTextAlignment:NSTextAlignmentCenter];
        [titleLab setFont:FontCustomSize(16)];
        titleLab.numberOfLines = 0;
        titleLab.frame = CGRectMake(0, 0, contentView.width, ActionSheetButtonHeight);
        [contentView addSubview:titleLab];
        
        //根据文字类型设置标题
        if ([title isKindOfClass:[NSString class]]) {
            [titleLab setText:title];
            
        } else if([title isKindOfClass:[NSAttributedString class]]){
            [titleLab setAttributedText:title];
        }
        
        //线条
        UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(titleLab.frame), Screen_Width, 0.5f)];
        [line setImage:[UIImage imageNamed:@"cellLine"]];
        [contentView addSubview:line];
        
        titleHY = CGRectGetMaxY(line.frame);
    }
    
    //所有按钮标题
    NSMutableArray *allbuttontitleArr = [NSMutableArray arrayWithArray:buttonTitleArr];
    
    //兼容按钮超过五个的场景就滚动
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, titleHY, Screen_Width, 100)];
    scrollView.delaysContentTouches = NO;
    [contentView addSubview:scrollView];
    
    [self.actionSheetButtonArr removeAllObjects];
    //设置所有按钮
    for (int i = 0 ; i<allbuttontitleArr.count; i++) {
        
        UIButton *actionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [actionBtn setSize:CGSizeMake(Screen_Width, ActionSheetButtonHeight)];
        actionBtn.backgroundColor = WhiteColor;
        actionBtn.y = ActionSheetButtonHeight*i;
        actionBtn.tag = i+1;
        [actionBtn.titleLabel setFont:FontCustomSize(16)];
        [actionBtn addTarget:self action:@selector(actionBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [actionBtn setTitleColor:RGB(231, 231, 231) forState:UIControlStateDisabled];
        [actionBtn setTitleColor:Color_BlackFont forState:0];
        [actionBtn setBackgroundColor:RGB(231, 231, 231) forState:UIControlStateHighlighted];
        [scrollView addSubview:actionBtn];//把每个按钮添加到scrollView上
        [actionBtn setExclusiveTouch:YES];
        
        //添加所有actionSheet按钮
        [self.actionSheetButtonArr addObject:actionBtn];
        
        //根据文字类型设置actionBtn标题
        id buttonTitle = allbuttontitleArr[i];
        if ([buttonTitle isKindOfClass:[NSString class]]) {
            [actionBtn setTitle:buttonTitle forState:0];
            
        } else if([buttonTitle isKindOfClass:[NSAttributedString class]]){
            [actionBtn setAttributedTitle:buttonTitle forState:0];
        }
        
        //线条
        UIImageView *line = [[UIImageView alloc] init];
        [line setImage:[UIImage imageNamed:@"cellLine"]];
        [line setContentMode:UIViewContentModeCenter];
        [line setFrame:CGRectMake(0, 0, Screen_Width, 1.0f)];
        [actionBtn addSubview:line];
        
        if (i>4) { //不能超过5个按钮高度
            scrollView.height = ActionSheetButtonHeight*5;
            scrollView.bounces = YES;
        } else {
            scrollView.height = CGRectGetMaxY(actionBtn.frame);
            scrollView.bounces = NO;
        }
        scrollView.contentSize = CGSizeMake(Screen_Width, CGRectGetMaxY(actionBtn.frame));
    }
    
    //添加取消按钮
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setSize:CGSizeMake(Screen_Width, ActionSheetButtonHeight)];
    cancelBtn.backgroundColor = WhiteColor;
    cancelBtn.y = CGRectGetMaxY(scrollView.frame)+5;
    cancelBtn.tag = 0;
    [cancelBtn.titleLabel setFont:FontCustomSize(16)];
    [cancelBtn addTarget:self action:@selector(actionBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [cancelBtn setTitleColor:RGB(231, 231, 231) forState:UIControlStateDisabled];
    [cancelBtn setTitleColor:Color_BlackFont forState:0];
    [cancelBtn setBackgroundColor:RGB(231, 231, 231) forState:UIControlStateHighlighted];
    [contentView addSubview:cancelBtn];
    [cancelBtn setExclusiveTouch:YES];
    
    //根据文字类型设置取消按钮标题
    if ([cancelTitle isKindOfClass:[NSString class]]) {
        [cancelBtn setTitle:cancelTitle forState:0];
        
    } else if([cancelTitle isKindOfClass:[NSAttributedString class]]){
        [cancelBtn setAttributedTitle:cancelTitle forState:0];
    }
    
    //设置弹框主视图的高度
    contentView.height = CGRectGetMaxY(cancelBtn.frame);
    
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    [window endEditing:YES];
    [window addSubview:self];
}


/**
 *  获取ActionSheet上的指定按钮
 *  注意:index为所有按钮数组的角标(cancelButton的角标为0 ,其他依次加1)
 */
- (UIButton *)buttonAtIndex:(NSInteger)index
{
    if (self.actionSheetButtonArr.count>0) {
        for (UIButton *actionBtn in self.actionSheetButtonArr) {
            if ([actionBtn isKindOfClass:[UIButton class]] && actionBtn.tag == index) {
                return actionBtn;
            }
        }
    }
    return nil;
}


/**
 *  给ActionSheet的指定按钮设置标题
 *  注意:index为所有按钮数组的角标(cancelButton的角标为0 ,其他依次加1)
 */
- (void)setButtonTitleToIndex:(NSInteger)index title:(id)title enable:(BOOL)enable
{
    if (self.actionSheetButtonArr.count>0) {
        for (UIButton *actionBtn in self.actionSheetButtonArr) {
            
            if ([actionBtn isKindOfClass:[UIButton class]] && actionBtn.tag == index) {
                actionBtn.enabled = enable;
                
                //根据文字类型设置标题
                if ([title isKindOfClass:[NSString class]]) {
                    [actionBtn setTitle:title forState:0];
                    
                } else if([title isKindOfClass:[NSAttributedString class]]){
                    [actionBtn setAttributedTitle:title forState:0];
                }
                break;
            }
        }
    }
}


/**
 *  操作按钮事件
 */
- (void)actionBtnAction:(UIButton *)actionBtn
{
    NSLog(@"点击了ActionSheet弹框按钮==%zd",actionBtn.tag);
    if (actionBtn.tag == 0) { //取消按钮
        if (self.cancelBlock) {
            self.cancelBlock();
        }
    } else { //其他按钮
        if (self.buttonBlock) {
            self.buttonBlock(actionBtn.tag);
        }
    }    
    [self dismissGJActionSheet:nil];
}


/**
 *  显示弹框
 */
- (void)showGJActionSheet
{
    [UIView animateWithDuration:0.25f delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        [self setAlpha:1];
        self.contentView.y = Screen_Height - self.contentView.height;
    } completion:nil];
}

/**
 *  退出弹框
 */
- (void)dismissGJActionSheet:(id)sender
{
    [UIView animateWithDuration:0.2f delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                         self.contentView.y = Screen_Height;
                         self.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0];
                     } completion:^(BOOL finished) {
                         
                         if (sender) {
                             NSLog(@"点击了ActionSheet灰色背景消失");
                             if (self.cancelBlock) {
                                 self.cancelBlock();
                             }
                         }
                         
                         [self removeFromSuperview];
                     }];
}

- (void)dealloc
{
    NSLog(@"%s",__func__);
}
@end
